package com.ruoyi.ncpsy.service.impl;

import java.util.List;
import java.util.UUID;
import java.nio.charset.StandardCharsets;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.ncpsy.domain.NcpsyAgrProductArchive;
import com.ruoyi.ncpsy.domain.NcpsyArea;
import com.ruoyi.ncpsy.domain.NcpsyCropEvent;
import com.ruoyi.ncpsy.mapper.NcpsyAgrProductArchiveMapper;
import com.ruoyi.ncpsy.mapper.NcpsyAreaMapper;
import com.ruoyi.ncpsy.mapper.NcpsyCropEventMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.ncpsy.mapper.NcpsyAreaProductMapper;
import com.ruoyi.ncpsy.domain.NcpsyAreaProduct;
import com.ruoyi.ncpsy.service.INcpsyAreaProductService;

/**
 * 农产品管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-29
 */
@Service
public class NcpsyAreaProductServiceImpl implements INcpsyAreaProductService 
{
    @Autowired
    private NcpsyAreaProductMapper ncpsyAreaProductMapper;
    @Autowired
    private NcpsyAgrProductArchiveMapper ncpsyAgrProductArchiveMapper;
    @Autowired
    private NcpsyCropEventMapper ncpsyCropEventMapper;
    @Autowired
    private NcpsyAreaMapper ncpsyAreaMapper;
    /**
     * 查询农产品管理
     * 
     * @param cropId 农产品管理主键
     * @return 农产品管理
     */
    @Override
    public NcpsyAreaProduct selectNcpsyAreaProductByCropId(Long cropId)
    {
        return ncpsyAreaProductMapper.selectNcpsyAreaProductByCropId(cropId);
    }

    /**
     * 查询农产品管理列表
     * 
     * @param ncpsyAreaProduct 农产品管理
     * @return 农产品管理
     */
    @Override
    public List<NcpsyAreaProduct> selectNcpsyAreaProductList(NcpsyAreaProduct ncpsyAreaProduct)
    {
        List<NcpsyAreaProduct> ncpsyAreaProducts = ncpsyAreaProductMapper.selectNcpsyAreaProductList(ncpsyAreaProduct);
        ncpsyAreaProducts.forEach(ncpsyAreaProduct1 -> {
            System.out.println(ncpsyAreaProduct1.getCropId());
            long sign = ncpsyAreaProduct1.getCropId();
            NcpsyAgrProductArchive ncpsyAgrProductArchive = ncpsyAgrProductArchiveMapper.selectNcpsyAgrProductArchiveByCropId(sign);
            if (ncpsyAgrProductArchive != null) {
                ncpsyAreaProduct1.setCurrentStatus(ncpsyAgrProductArchive.getCurrentStatus());
                ncpsyAreaProduct1.setSuggestedRetailPrice(ncpsyAgrProductArchive.getSuggestedRetailPrice());
                System.out.println(ncpsyAreaProduct1.getCurrentStatus());
            }
        });
        return ncpsyAreaProducts;
    }

    /**
     * 新增农产品管理
     * 
     * @param ncpsyAreaProduct 农产品管理
     * @return 结果
     */
    @Override
    public int insertNcpsyAreaProduct(NcpsyAreaProduct ncpsyAreaProduct)
    {
        // 新增农产品档案
        NcpsyAgrProductArchive ncpsyAgrProductArchive = new NcpsyAgrProductArchive();
        // 生成基于传入字段的溯源码（UUID v3 风格，基于内容）
        if (ncpsyAreaProduct.getHash() == null || ncpsyAreaProduct.getHash().isEmpty()) {
            StringBuilder seedBuilder = new StringBuilder();
            if (ncpsyAreaProduct.getProductId() != null) seedBuilder.append("productId=").append(ncpsyAreaProduct.getProductId()).append('|');
            if (ncpsyAreaProduct.getAreaId() != null) seedBuilder.append("areaId=").append(ncpsyAreaProduct.getAreaId()).append('|');
            if (ncpsyAreaProduct.getUserId() != null) seedBuilder.append("userId=").append(ncpsyAreaProduct.getUserId()).append('|');
            if (ncpsyAreaProduct.getCropName() != null) seedBuilder.append("cropName=").append(ncpsyAreaProduct.getCropName()).append('|');
            if (ncpsyAreaProduct.getBeginTime() != null) seedBuilder.append("beginTime=").append(ncpsyAreaProduct.getBeginTime().getTime()).append('|');
            if (ncpsyAreaProduct.getReapTime() != null) seedBuilder.append("reapTime=").append(ncpsyAreaProduct.getReapTime().getTime()).append('|');
            if (ncpsyAreaProduct.getEstimatedTotalYield() != null) seedBuilder.append("estimatedTotalYield=").append(ncpsyAreaProduct.getEstimatedTotalYield()).append('|');
            if (ncpsyAreaProduct.getYieldUnit() != null) seedBuilder.append("yieldUnit=").append(ncpsyAreaProduct.getYieldUnit()).append('|');
            if (ncpsyAreaProduct.getPlantingAravage() != null) seedBuilder.append("plantingAravage=").append(ncpsyAreaProduct.getPlantingAravage()).append('|');

            String seed = seedBuilder.toString();
            if (!seed.isEmpty()) {
                String uuid = UUID.nameUUIDFromBytes(seed.getBytes(StandardCharsets.UTF_8)).toString();
                ncpsyAgrProductArchive.setTraceabilityCode(uuid);
            } else {
                // 兜底：当没有可用字段时，使用随机UUID
                ncpsyAgrProductArchive.setTraceabilityCode(UUID.randomUUID().toString());
            }
        }
        ncpsyAreaProduct.setCreateTime(DateUtils.getNowDate());

        ncpsyAreaProductMapper.insertNcpsyAreaProduct(ncpsyAreaProduct);
//        System.out.println(ncpsyAreaProduct.getCropId());

        NcpsyArea ncpsyArea = ncpsyAreaMapper.selectNcpsyAreaByAreaId(ncpsyAreaProduct.getAreaId());
        String areaAddress = ncpsyArea.getAreaAddress();


        ncpsyAgrProductArchive.setCropId(ncpsyAreaProduct.getCropId());
        ncpsyAgrProductArchive.setUserId(ncpsyAreaProduct.getUserId());
        ncpsyAgrProductArchive.setCropName(ncpsyAreaProduct.getCropName());
        ncpsyAgrProductArchive.setCreateTime(DateUtils.getNowDate());
        ncpsyAgrProductArchive.setPlantingLocation(areaAddress);
        ncpsyAgrProductArchiveMapper.insertNcpsyAgrProductArchive(ncpsyAgrProductArchive);

        //新增事件列表
        NcpsyCropEvent ncpsyCropEvent = new NcpsyCropEvent();
        ncpsyCropEvent.setCropId(ncpsyAreaProduct.getCropId());
        ncpsyCropEvent.setUserId(ncpsyAreaProduct.getUserId());
        ncpsyCropEvent.setCreateTime(DateUtils.getNowDate());
        ncpsyCropEventMapper.insertNcpsyCropEvent(ncpsyCropEvent);
        return 1;
    }

    /**
     * 修改农产品管理
     * 
     * @param ncpsyAreaProduct 农产品管理
     * @return 结果
     */
    @Override
    public int updateNcpsyAreaProduct(NcpsyAreaProduct ncpsyAreaProduct)
    {
        ncpsyAreaProduct.setUpdateTime(DateUtils.getNowDate());
        return ncpsyAreaProductMapper.updateNcpsyAreaProduct(ncpsyAreaProduct);
    }

    /**
     * 批量删除农产品管理
     * 
     * @param cropIds 需要删除的农产品管理主键
     * @return 结果
     */
    @Override
    public int deleteNcpsyAreaProductByCropIds(Long[] cropIds)
    {
        ncpsyAgrProductArchiveMapper.deleteNcpsyAgrProductArchiveByCropIds(cropIds);
        ncpsyCropEventMapper.deleteNcpsyAgrProductEventByCropIds(cropIds);
        return ncpsyAreaProductMapper.deleteNcpsyAreaProductByCropIds(cropIds);
    }

    /**
     * 删除农产品管理信息
     * 
     * @param cropId 农产品管理主键
     * @return 结果
     */
    @Override
    public int deleteNcpsyAreaProductByCropId(Long cropId)
    {
        ncpsyAgrProductArchiveMapper.deleteNcpsyAgrProductArchiveByCropIds(new Long[]{cropId});
        ncpsyCropEventMapper.deleteNcpsyAgrProductEventByCropIds(new Long[]{cropId});
        return ncpsyAreaProductMapper.deleteNcpsyAreaProductByCropId(cropId);
    }
}
